package com.baizhi.utli;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    private static SqlSessionFactory factory=null;
    private static ThreadLocal<SqlSession> tl=new ThreadLocal<>();
    static{
        try {
            InputStream in= Resources.getResourceAsStream("mybatis-config.xml");
            factory =new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static SqlSession openSession(){
        //获取sqlSession
        //首先从线程中获取SqlSession

        SqlSession sqlSession=tl.get();
        if(sqlSession==null){
            sqlSession=factory.openSession();
            tl.set(sqlSession);
        }
        return sqlSession;
    }

    public static void close(SqlSession sqlSession){
        tl.remove();
        sqlSession.close();
    }
}
